package org.visionlibrary.image.filters.thresholding;

import java.awt.Point;
import java.util.Collections;
import java.util.Vector;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.model.WindowFilter;


public class MedianThreshold extends WindowFilter {
	protected int width;
	protected int height;

	public MedianThreshold(int width, int height) {
		this.width = width;
		this.height = height;
	}

	public MedianThreshold(int size) {
		this(size, size);
	}

	public MedianThreshold() {
		this(3);
	}

	protected int getNewPixelVal(TiledImage src, Point p, int channel) {
		Vector<Integer> medianv = new Vector<Integer>();

		Point pIter = new Point();
		for (pIter.y = 0; pIter.y < windowHeight; pIter.y++)
			for (pIter.x = 0; pIter.x < windowWidth; pIter.x++) {
				int val = getWindowPixelVal(src, pIter, channel);
				medianv.add(new Integer(val));
			}

		Collections.sort(medianv);
		int currentPixelVal = getWindowPixelVal(src, dstPointInWindow, channel);
		int threshold = medianv.elementAt(medianv.size() / 2).intValue();

		if (currentPixelVal < threshold)
			return 255;
		else
			return 0;
	}

	protected void setWindowProperties() {
		windowWidth = width;
		windowHeight = height;
		dstPointInWindow = new Point(width / 2, height / 2);
	}
}